package com.say.utils.weixin;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

/**
 * 媒体接口类
*/

import com.alibaba.fastjson.JSONObject;
import com.say.framework.core.util.StringUtil;
import com.say.framework.core.util.SystemResourceLocator;
import com.say.framework.idworker.IdWorker;
import com.say.utils.DateHelper;
import com.say.utils.SysParentFile;
public class MUDload {
	 private static Logger log = LoggerFactory.getLogger(MUDload.class);
	 //public static String file_path = "D:\\";
	/**
	 * 上传媒体文件
	 * @param accessToken 接口访问凭证
	 * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
	 * @param media form-data中媒体文件标识，有filename、filelength、content-type等信息
	 * @param mediaFileUrl 媒体文件的url
	 * 上传的媒体文件限制
     * 图片（image）:1MB，支持JPG格式
     * 语音（voice）：2MB，播放长度不超过60s，支持AMR格式
     * 视频（video）：10MB，支持MP4格式
     * 普通文件（file）：10MB
	 * @throws Exception 
	 * */
	public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) throws Exception {
    	File path = null;
 	    try {
 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
 	    } catch (FileNotFoundException e) {
 	    	e.printStackTrace();
 	    }
    	String file_path=SysParentFile.getParentFile();
    	
		WeixinMedia weixinMedia = new WeixinMedia();
		  String result = null;  
		// 拼装请求地址
		String uploadMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
		uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
	    File file = new File(file_path+mediaFileUrl);  
	    if (!file.exists() || !file.isFile()) {  
	    	throw new IOException("文件不存在");  
	    }  
	    /** 
	    * 第一部分 
	    */  
	    URL urlObj = new URL(uploadMediaUrl);  
	    
	    
	    
        	TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象   
            SSLSocketFactory ssf = sslContext.getSocketFactory(); 
            HttpsURLConnection	 con = (HttpsURLConnection) urlObj.openConnection();  
            con.setSSLSocketFactory(ssf);  
             // 设置请求方式（GET/POST）   
             
             
             
	    // 连接  
	    /** 
	    * 设置关键值 
	    */  
	    con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式  
	    con.setDoInput(true);  
	    con.setDoOutput(true);  
	    con.setUseCaches(false); // post方式不能使用缓存  
	  
	  
	    // 设置请求头信息  
	    con.setRequestProperty("Connection", "Keep-Alive");  
	    con.setRequestProperty("Charset", "UTF-8");  
	  
	  
	    // 设置边界  
	    String BOUNDARY = "----------" + System.currentTimeMillis();  
	    con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
	  
	  
	    // 请求正文信息  
	  
	  
	    // 第一部分：  
	    StringBuilder sb = new StringBuilder();  
	    sb.append("--"); // 必须多两道线  
	    sb.append(BOUNDARY);  
	    sb.append("\r\n");  
	    sb.append("Content-Disposition: form-data;name=\"file\";filename=\""  
	    + file.getName() + "\"\r\n");  
	    sb.append("Content-Type:application/octet-stream\r\n\r\n");  
	  
	  
	    byte[] head = sb.toString().getBytes("utf-8");  
	  
	  
	    // 获得输出流  
	    OutputStream out = new DataOutputStream(con.getOutputStream());  
	    // 输出表头  
	    out.write(head);  
	  
	  
	    // 文件正文部分  
	    // 把文件已流文件的方式 推入到url中  
	    DataInputStream in = new DataInputStream(new FileInputStream(file));  
	    int bytes = 0;  
	    byte[] bufferOut = new byte[1024];  
	    while ((bytes = in.read(bufferOut)) != -1) {  
	    out.write(bufferOut, 0, bytes);  
	    }  
	    in.close();  
	  
	  
	    // 结尾部分  
	    byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
	  
	    out.write(foot);  
	    out.flush();  
	    out.close();  
	  
	  
	    StringBuffer buffer = new StringBuffer();  
	    BufferedReader reader = null;  
	    try {  
	    // 定义BufferedReader输入流来读取URL的响应  
	    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
	    String line = null;  
	    while ((line = reader.readLine()) != null) {  
	    buffer.append(line);  
	    }  
	    if(result==null){  
	    result = buffer.toString();  
	    }  
	    } catch (IOException e) {  
		log.error("发送POST请求出现异常！", e);
	    e.printStackTrace();  
	    throw new IOException("数据读取异常");  
	    } finally {  
	    if(reader!=null){  
	    reader.close();  
	    }  
	  
	    }  
	  
	    JSONObject jsonObj = JSONObject.parseObject(result);  
	    String mediaId = jsonObj.getString("media_id");  
	    weixinMedia.setMediaId(mediaId);
	    weixinMedia.setCreatedAt(jsonObj.getInteger("created_at"));
	    weixinMedia.setType(jsonObj.getString("type"));
	    return weixinMedia;  	   
	}
	
	/**
	 * 获取媒体文件
	 * @param accessToken 接口访问凭证
	 * @param  媒体文件id
	 * @param savePath 文件在服务器上的存储路径
	 * */
	public static String downloadMedia(String accessToken, String mediaId, String savePath) {
    	File path = null;
 	    try {
 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
 	    } catch (FileNotFoundException e) {
 	    	e.printStackTrace();
 	    }
    	String file_path=SysParentFile.getParentFile();
		
		String filePath = null;
		// 拼接请求地址
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		//String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
		log.info("requestUrl="+requestUrl);
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			if (!savePath.endsWith("/")) {
				savePath += "/";
			}
			log.info("Content-Type="+conn.getHeaderField("Content-Type"));
			// 根据内容类型获取扩展名
			String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
			// 将mediaId作为文件名
			File  f = new File(file_path+savePath);
			if (!f.exists()) {
				f.mkdirs();
			}
			filePath = savePath + mediaId + fileExt;
            String absolutePath = file_path +filePath;
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(absolutePath));
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();

			conn.disconnect();
			log.info("下载媒体文件成功，filePath=" + absolutePath);
		} catch (Exception e) {
			//filePath = null;
			log.error("下载媒体文件失败：%s", e);
			return null;
		}
		return filePath;
	}

	   public static String  downloadImage(String requestUrl){
	    	File path = null;
	 	    try {
	 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
	 	    } catch (FileNotFoundException e) {
	 	    	e.printStackTrace();
	 	    }
	    	String file_path=SysParentFile.getParentFile();

           if(StringUtil.isBlank(requestUrl)){
              return  null;
           }

		   String filePath = null;
		   String absolutePath =null;
			// 拼接请求地址
			try {
		            URL url = new URL(requestUrl);  
		            HttpsURLConnection httpUrlConn = null;
		            HttpURLConnection conn = null;
		            if (url.getProtocol().toLowerCase().equals("https")) {
		            	TrustManager[] tm = { new MyX509TrustManager() };  
			            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
			            sslContext.init(null, tm, new java.security.SecureRandom());  
			            // 从上述SSLContext对象中得到SSLSocketFactory对象   
			            SSLSocketFactory ssf = sslContext.getSocketFactory(); 
		            	 httpUrlConn = (HttpsURLConnection) url.openConnection();  
		            	 httpUrlConn.setSSLSocketFactory(ssf);  
			             httpUrlConn.setDoOutput(true);  
			             httpUrlConn.setDoInput(true);  
			             httpUrlConn.setUseCaches(false);  
			             // 设置请求方式（GET/POST）   
			             httpUrlConn.setRequestMethod("GET");
		            }else{
		            	conn = (HttpURLConnection) url.openConnection();
						conn.setDoInput(true);
						conn.setRequestMethod("GET");
						conn.setConnectTimeout(30000);
						conn.setReadTimeout(30000);
		            }
		           
		            
				
				
				
				String savePath =  "/userimg"+DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd");
				if (!savePath.endsWith("/")) {
					savePath += "/";
				}
				// 根据内容类型获取扩展名
				String fileExt ="";
				if (url.getProtocol().toLowerCase().equals("https")) {
					fileExt = WeixinUtil.getFileEndWitsh(httpUrlConn.getHeaderField("Content-Type"));
				}else{
					fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
				}
				// 将mediaId作为文件名
				File  f = new File(file_path+savePath);
				if (!f.exists()) {
					f.mkdirs();
				}
				filePath = savePath + IdWorker.generateId() + fileExt;
	             absolutePath = file_path +filePath;
	            BufferedInputStream bis = null;
	            if (url.getProtocol().toLowerCase().equals("https")) {
	            	bis = new BufferedInputStream(httpUrlConn.getInputStream());
	            }else{
	            	bis = new BufferedInputStream(conn.getInputStream());
	            }
				FileOutputStream fos = new FileOutputStream(new File(absolutePath));
				byte[] buf = new byte[8096];
				int size = 0;
				while ((size = bis.read(buf)) != -1)
					fos.write(buf, 0, size);
				fos.close();
				bis.close();
				if (url.getProtocol().toLowerCase().equals("https")) {
					httpUrlConn.disconnect();
				}else{
					conn.disconnect();
				}
				log.info("下载用户头像成功，filePath=" + absolutePath);
			} catch (Exception e) {
				//filePath = null;
				log.error("下载用户头像失败：%s", e);
				return null;
			}
			if(filePath!=null){
			}


			return filePath;
	   }
	   
	   

		/**
		 * 上传媒体文件
		 * @param accessToken 接口访问凭证
		 * @param type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
		 * @param media form-data中媒体文件标识，有filename、filelength、content-type等信息
		 * @param mediaFileUrl 媒体文件的url
		 * 上传的媒体文件限制
	     * 图片（image）:1MB，支持JPG格式
	     * 语音（voice）：2MB，播放长度不超过60s，支持AMR格式
	     * 视频（video）：10MB，支持MP4格式
	     * 普通文件（file）：10MB
		 * @throws Exception 
		 * */
		public static JSONObject uploadMediaJson(String accessToken, String type, String mediaFileUrl) throws Exception {
	    	File path = null;
	 	    try {
	 	    	path = new File(ResourceUtils.getURL("classpath:").getPath());
	 	    } catch (FileNotFoundException e) {
	 	    	e.printStackTrace();
	 	    }
	    	String file_path=SysParentFile.getParentFile();;
	    	
			String result = null;  
			// 拼装请求地址
			 // https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
			String uploadMediaUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN&type=TYPE";
			uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
		    File file = new File(file_path+mediaFileUrl);  
		    if (!file.exists() || !file.isFile()) {  
		    	throw new IOException("文件不存在");  
		    }  
		    /** 
		    * 第一部分 
		    */  
		    URL urlObj = new URL(uploadMediaUrl);  
		    // 连接  
			TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象   
            SSLSocketFactory ssf = sslContext.getSocketFactory(); 
            HttpsURLConnection	 con = (HttpsURLConnection) urlObj.openConnection();  
            con.setSSLSocketFactory(ssf);    
		    /** 
		    * 设置关键值 
		    */  
		    con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式  
		    con.setDoInput(true);  
		    con.setDoOutput(true);  
		    con.setUseCaches(false); // post方式不能使用缓存  
		  
		  
		    // 设置请求头信息  
		    con.setRequestProperty("Connection", "Keep-Alive");  
		    con.setRequestProperty("Charset", "UTF-8");  
		  
		  
		    // 设置边界  
		    String BOUNDARY = "----------" + System.currentTimeMillis();  
		    con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);  
		  
		  
		    // 请求正文信息  
		  
		  
		    // 第一部分：  
		    StringBuilder sb = new StringBuilder();  
		    sb.append("--"); // 必须多两道线  
		    sb.append(BOUNDARY);  
		    sb.append("\r\n");  
		    sb.append("Content-Disposition: form-data;name=\"file\";filename=\""  
		    + file.getName() + "\"\r\n");  
		    sb.append("Content-Type:application/octet-stream\r\n\r\n");  
		  
		  
		    byte[] head = sb.toString().getBytes("utf-8");  
		  
		  
		    // 获得输出流  
		    OutputStream out = new DataOutputStream(con.getOutputStream());  
		    // 输出表头  
		    out.write(head);  
		  
		  
		    // 文件正文部分  
		    // 把文件已流文件的方式 推入到url中  
		    DataInputStream in = new DataInputStream(new FileInputStream(file));  
		    int bytes = 0;  
		    byte[] bufferOut = new byte[1024];  
		    while ((bytes = in.read(bufferOut)) != -1) {  
		    out.write(bufferOut, 0, bytes);  
		    }  
		    in.close();  
		  
		  
		    // 结尾部分  
		    byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线  
		  
		    out.write(foot);  
		    out.flush();  
		    out.close();  
		  
		  
		    StringBuffer buffer = new StringBuffer();  
		    BufferedReader reader = null;  
		    try {  
		    // 定义BufferedReader输入流来读取URL的响应  
		    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));  
		    String line = null;  
		    while ((line = reader.readLine()) != null) {  
		    buffer.append(line);  
		    }  
		    if(result==null){  
		    result = buffer.toString();  
		    }  
		    } catch (IOException e) {  
			log.error("发送POST请求出现异常！", e);
		    e.printStackTrace();  
		    throw new IOException("数据读取异常");  
		    } finally {  
		    if(reader!=null){  
		    reader.close();  
		    }  
		  
		    }  
		  
		    JSONObject jsonObj = JSONObject.parseObject(result);  
		    return jsonObj;  	   
		}
}